//
//  UserVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/15.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "UserVC.h"
#import "LoginVC.h"
#import <UIColor+Wonderful.h>
#import "UserCell.h"
#import "AboutUsVC.h"
@interface UserVC () <UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, retain) UIButton *loginButton;/**< 登录按钮 */
@property (nonatomic, retain) UIImageView *backImg;/**< 背景图片 */
@property (nonatomic, retain) UIImageView *userImg;/**< 用户头像 */
@property (nonatomic, retain) UILabel *usernameLabel;/**< 用户名 */
@property (nonatomic, retain) UICollectionView *collectionview;/**< collectionview */
@property (nonatomic, retain) NSMutableArray *dataArr;/**< 保存数据数组 */
@property (nonatomic, retain) NSString *imgPath;/**< 保存图片路径 */
@end

@implementation UserVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //navigation设置
    self.navigationItem.title = @"我的";
    
    // 创建视图
    [self createSubviews];
    // 调用可以更改图片路径
//    [self imgChangeAction];
    
}

/// 创建视图方法
- (void)createSubviews
{
    // 右侧登陆按钮
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(0, 0, 50, 50);
    
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:[UIColor peachRed] forState:UIControlStateNormal];
    [self.loginButton setTitle:@"注销" forState:UIControlStateSelected];
    [self.loginButton setTitleColor:[UIColor peachRed] forState:UIControlStateSelected];
    [self.loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem 	= [[[UIBarButtonItem alloc] initWithCustomView:self.loginButton] autorelease];
    
    //backImg
    self.backImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height / 3.5)];
    _backImg.image = [UIImage imageNamed:@"backImg6.jpg"];
    [self.view addSubview:_backImg];
    [_backImg release];
    
    //用户头像
    
    self.userImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.height / 10.5, self.view.frame.size.height / 10.5)];
    _userImg.center = CGPointMake(_backImg.center.x, _backImg.center.y);
    _userImg.image = [UIImage imageNamed:@"userImg2.jpg"];
    _userImg.layer.cornerRadius = _userImg.frame.size.width / 2;
    _userImg.clipsToBounds = YES;
    // 开启用户交互
    _userImg.userInteractionEnabled = YES;
    [self.view addSubview:_userImg];
    [_userImg release];
    
    // 判断保存的头像图片是不是已经存在 如果存在就显示
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user dataForKey:@"userImg"]) {
        [_userImg setImage:[UIImage imageWithData:[user dataForKey:@"userImg"]]];
    }
    
    //给头像添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeImgAction:)];
    [self.userImg addGestureRecognizer:tap];
    [tap release];
    
    
    //usernameLabel;
    self.usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, _backImg.frame.size.height / 6)];
    _usernameLabel.center = CGPointMake(_backImg.center.x, _backImg.center.y + _backImg.frame.size.height / 3);
    _usernameLabel.backgroundColor = [UIColor aquamarine];
    _usernameLabel.textColor = [UIColor aquamarine];
    _usernameLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_usernameLabel];
    [_usernameLabel release];
    
    //collectionview
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 50) / 4, (self.view.frame.size.width - 50) / 3.5);
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);
    self.collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 3.5 + 64, self.view.frame.size.width, self.view.frame.size.height / 2) collectionViewLayout:layout];
    // 取消边缘弹动
//    _collectionview.bounces = NO;
    _collectionview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionview];
    [_collectionview release];
    
    // 签订协议
    _collectionview.delegate = self;
    _collectionview.dataSource = self;
    // 注册重用池
    [_collectionview registerClass:[UserCell class] forCellWithReuseIdentifier:@"cell"];
    
    
}

/// 设置collectionview的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 6;
}

/// 设置cell

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.item == 0) {
        cell.nameLabel.text = @"我的精选";
        cell.imageview.image = [UIImage imageNamed:@"C13"];
//        cell.backgroundColor = [UIColor yellowColor];
    }else if (indexPath.item == 1) {
        cell.nameLabel.text = @"我的攻略";
        cell.imageview.image = [UIImage imageNamed:@"C14"];
    }else if (indexPath.item == 2) {
        cell.nameLabel.text = @"我的专题";
        cell.imageview.image = [UIImage imageNamed:@"C15"];
    }else if (indexPath.item == 3) {
        cell.nameLabel.text = @"夜间模式";
        cell.imageview.image = [UIImage imageNamed:@"C16"];
    }else if (indexPath.item == 4){
        cell.nameLabel.text = @"关于我们";
        cell.imageview.image = [UIImage imageNamed:@"C17"];
    }else{
        cell.nameLabel.text = @"清除缓存";
        cell.imageview.image = [UIImage imageNamed:@"C18"];
    }
    
    return cell;
}



///右侧登录按钮方法
- (void)login
{
    LoginVC *loginVC = [[LoginVC alloc] init];
    UINavigationController *loginNavi = [[UINavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:loginNavi animated:YES completion:^{
        
    }];
}

/// 点击cell进入详情
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 清除缓存
    if (indexPath.row == 5) {
        
        // 获取缓存文件的大小
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSDictionary *dic = [[NSFileManager defaultManager] attributesOfItemAtPath:cachePath error:nil];
        NSString *size = [dic objectForKey:NSFileSize];
        NSString *messageStr = [NSString stringWithFormat:@"是否确认清除%@M内存?", size];
        
        // 提示是不是清除缓存
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:messageStr preferredStyle:UIAlertControllerStyleAlert];
        // 取消
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        //确定
        UIAlertAction *certain = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //清除掉cache文件夹
            NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            NSFileManager *fManage = [NSFileManager defaultManager];
            [fManage removeItemAtPath:path error:nil];
            
        }];
        [alertView addAction:cancel];
        [alertView addAction:certain];
        
        [self presentViewController:alertView animated:YES completion:^{
            
            
        }];
    }
    if (indexPath.row == 4) {
        AboutUsVC *aboutVC = [[AboutUsVC alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
    }
}

/// 点击更换头像的方法
- (void)changeImgAction:(UITapGestureRecognizer *)tap
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    // 静态方法判断设备是否支持图库功能
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    // 签订协议
    pickerImage.delegate = self;
    //是否可以编辑, 剪裁
    pickerImage.allowsEditing = YES;
    // 跳转到相册界面
    [self presentViewController:pickerImage animated:YES completion:^{
        
    }];
    [pickerImage release];
}

#pragma mark - 相册协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //将编辑后的图片保存在Image中
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //当图片不为空的时候显示并保存图片
    if (image != nil) {
        //图片显示在界面
        self.userImg.image = image;
        
        // 将图片保存到沙盒路径下
        // 把图片转化成NSData类型的数据来保存文件
        NSData *data;
        // 如果图片是png图像
        if (UIImagePNGRepresentation(image)) {
            // 返回png图像
            data = UIImagePNGRepresentation(image);
        }else{
            // 返回JPEG图像
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        [[NSFileManager defaultManager] createFileAtPath:self.imgPath contents:data attributes:nil];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        // 将图片保存在单例中
        
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"userImg"];
    }
}

#pragma mark - 点击图片更换图片路径
//- (void)imgChangeAction
//{
//    //更换图片
//    //获取Documents文件路径
//    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
//    //指定新建文件夹路径
//    NSString *imagePath = [documentPath stringByAppendingString:@"imageFile"];
//    // 创建imagFile文件夹
//    [[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
//    // 保存图片的路径
//    self.imgPath = [imagePath stringByAppendingString:@"image.png"];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
